package br.com.view;

import br.com.dao.ConectaBanco;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;

/**
 *
 * @author Cícero
 */
public class Frm_EntradaEpi extends javax.swing.JFrame {

    ConectaBanco conexao = new ConectaBanco();

    int valor1 = 0, valor2 = 0, total,codEpi,codFornecedor;
    String opcao,epiEntrada,fornecedorEntrada;

    /**
     * Creates new form Frm_EntradaEpi
     */
    public Frm_EntradaEpi() {
        conexao.conexao();
        initComponents();        
        ComboEpi();
        ComboFornecedor();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGroupModoEntrada = new javax.swing.ButtonGroup();
        lblEntradaEpi = new javax.swing.JLabel();
        lblIdEntrada = new javax.swing.JLabel();
        lblQuantidade = new javax.swing.JLabel();
        lblNumeroNF = new javax.swing.JLabel();
        textIdEntrada = new javax.swing.JTextField();
        textQuantidade = new javax.swing.JTextField();
        boxFornecedor = new javax.swing.JComboBox();
        lblEscoFornecedor = new javax.swing.JLabel();
        lblData = new javax.swing.JLabel();
        boxEpi = new javax.swing.JComboBox();
        lblEscoEPI = new javax.swing.JLabel();
        btnNovo = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        btnSalvar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        panelModoEntrada = new javax.swing.JPanel();
        lblUnidades = new javax.swing.JLabel();
        radioCaixa = new javax.swing.JRadioButton();
        radioUnidade = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        textNcaixa = new javax.swing.JTextField();
        textUcaixa = new javax.swing.JTextField();
        btnCalcular = new javax.swing.JButton();
        textNota = new javax.swing.JTextField();
        formattedData = new javax.swing.JFormattedTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("SysEPI - Entrada de EPI's");
        setResizable(false);
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowActivated(java.awt.event.WindowEvent evt) {
                formWindowActivated(evt);
            }
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        lblEntradaEpi.setFont(new java.awt.Font("Tahoma", 3, 18)); // NOI18N
        lblEntradaEpi.setText("Entrada do EPI");
        getContentPane().add(lblEntradaEpi, new org.netbeans.lib.awtextra.AbsoluteConstraints(265, 19, 150, -1));

        lblIdEntrada.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblIdEntrada.setText("Codigo:");
        getContentPane().add(lblIdEntrada, new org.netbeans.lib.awtextra.AbsoluteConstraints(85, 70, -1, -1));

        lblQuantidade.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblQuantidade.setText("Quantidade:");
        getContentPane().add(lblQuantidade, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 230, -1, -1));

        lblNumeroNF.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblNumeroNF.setText("Número NF:");
        getContentPane().add(lblNumeroNF, new org.netbeans.lib.awtextra.AbsoluteConstraints(447, 70, -1, -1));

        textIdEntrada.setEnabled(false);
        getContentPane().add(textIdEntrada, new org.netbeans.lib.awtextra.AbsoluteConstraints(136, 68, 50, -1));

        textQuantidade.setEnabled(false);
        textQuantidade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textQuantidadeActionPerformed(evt);
            }
        });
        getContentPane().add(textQuantidade, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 230, 82, -1));

        boxFornecedor.setEnabled(false);
        getContentPane().add(boxFornecedor, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 160, 380, -1));

        lblEscoFornecedor.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblEscoFornecedor.setText("Escolha Fornecedor:");
        getContentPane().add(lblEscoFornecedor, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 160, 124, -1));

        lblData.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblData.setText("Data Entrada:");
        getContentPane().add(lblData, new org.netbeans.lib.awtextra.AbsoluteConstraints(221, 70, -1, -1));

        boxEpi.setEnabled(false);
        getContentPane().add(boxEpi, new org.netbeans.lib.awtextra.AbsoluteConstraints(233, 108, 300, -1));

        lblEscoEPI.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblEscoEPI.setText("Escolha EPI:");
        getContentPane().add(lblEscoEPI, new org.netbeans.lib.awtextra.AbsoluteConstraints(150, 110, -1, -1));

        btnNovo.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnNovo.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon(42).png"))); // NOI18N
        btnNovo.setText("Nova Entrada");
        btnNovo.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnNovoActionPerformed(evt);
            }
        });
        getContentPane().add(btnNovo, new org.netbeans.lib.awtextra.AbsoluteConstraints(60, 320, -1, -1));

        btnCancelar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnCancelar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (4).png"))); // NOI18N
        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });
        getContentPane().add(btnCancelar, new org.netbeans.lib.awtextra.AbsoluteConstraints(250, 320, -1, -1));

        btnSalvar.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        btnSalvar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icones sysepi/favicon (29).png"))); // NOI18N
        btnSalvar.setText("Salvar");
        btnSalvar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSalvarActionPerformed(evt);
            }
        });
        getContentPane().add(btnSalvar, new org.netbeans.lib.awtextra.AbsoluteConstraints(550, 320, -1, -1));

        jSeparator1.setForeground(new java.awt.Color(0, 102, 102));
        getContentPane().add(jSeparator1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 140, 680, -1));

        panelModoEntrada.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 102, 102)));
        panelModoEntrada.setEnabled(false);

        lblUnidades.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        lblUnidades.setText("Modos de Entrada:");

        btnGroupModoEntrada.add(radioCaixa);
        radioCaixa.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        radioCaixa.setText("Caixa");
        radioCaixa.setActionCommand("caixa");
        radioCaixa.setEnabled(false);
        radioCaixa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioCaixaActionPerformed(evt);
            }
        });

        btnGroupModoEntrada.add(radioUnidade);
        radioUnidade.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        radioUnidade.setText("Unidade");
        radioUnidade.setActionCommand("unidade");
        radioUnidade.setEnabled(false);
        radioUnidade.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioUnidadeActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panelModoEntradaLayout = new javax.swing.GroupLayout(panelModoEntrada);
        panelModoEntrada.setLayout(panelModoEntradaLayout);
        panelModoEntradaLayout.setHorizontalGroup(
            panelModoEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelModoEntradaLayout.createSequentialGroup()
                .addContainerGap(12, Short.MAX_VALUE)
                .addGroup(panelModoEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelModoEntradaLayout.createSequentialGroup()
                        .addComponent(lblUnidades)
                        .addGap(23, 23, 23))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panelModoEntradaLayout.createSequentialGroup()
                        .addComponent(radioUnidade)
                        .addGap(18, 18, 18)
                        .addComponent(radioCaixa)
                        .addContainerGap())))
        );
        panelModoEntradaLayout.setVerticalGroup(
            panelModoEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panelModoEntradaLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblUnidades)
                .addGap(18, 18, 18)
                .addGroup(panelModoEntradaLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(radioCaixa)
                    .addComponent(radioUnidade))
                .addContainerGap(21, Short.MAX_VALUE))
        );

        getContentPane().add(panelModoEntrada, new org.netbeans.lib.awtextra.AbsoluteConstraints(30, 200, 170, 90));

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Numeros de Caixa");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 200, -1, -1));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Unidades da Caixa");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 250, -1, -1));

        textNcaixa.setEnabled(false);
        getContentPane().add(textNcaixa, new org.netbeans.lib.awtextra.AbsoluteConstraints(220, 220, 70, -1));

        textUcaixa.setEnabled(false);
        getContentPane().add(textUcaixa, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 270, 100, -1));

        btnCalcular.setText("Calcular");
        btnCalcular.setEnabled(false);
        btnCalcular.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCalcularActionPerformed(evt);
            }
        });
        getContentPane().add(btnCalcular, new org.netbeans.lib.awtextra.AbsoluteConstraints(340, 230, -1, -1));

        textNota.setEnabled(false);
        getContentPane().add(textNota, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 70, 130, -1));

        try {
            formattedData.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##/##/####")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        formattedData.setEnabled(false);
        getContentPane().add(formattedData, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 70, 110, -1));

        setSize(new java.awt.Dimension(722, 395));
        setLocationRelativeTo(null);
    }// </editor-fold>//GEN-END:initComponents

    private void textQuantidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_textQuantidadeActionPerformed
       
    }//GEN-LAST:event_textQuantidadeActionPerformed

    private void btnNovoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnNovoActionPerformed
        formattedData.setText(new SimpleDateFormat("dd/MM/yyyy").format(new Date(System.currentTimeMillis())));
        Novo();
    }//GEN-LAST:event_btnNovoActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        Cancelar();
        conexao.desconecta();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnSalvarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSalvarActionPerformed
        epiEntrada =  (String) boxEpi.getSelectedItem();
        fornecedorEntrada = (String) boxFornecedor.getSelectedItem();
        buscaCodEpi();
        buscaCodFornecedor();
        conexao.conexao();
        String sqlInserir = ("insert into entradaepi (quantidade_entrada, numero_nf_entrada, data_entrada, tipo_unidade_entrada, idfabricante, idcad_epi, Numeros_caixa_entrada, unidades_caixa_entrada) values (?,?,?,?,?,?,?,?)");             
        try {
            PreparedStatement pst = conexao.con.prepareStatement(sqlInserir);
            pst.setInt(1, Integer.parseInt(textQuantidade.getText().trim()));
            pst.setInt(2, Integer.parseInt(textNota.getText().trim()));
            pst.setDate(3, converteData(formattedData.getText()));
            pst.setString(4, btnGroupModoEntrada.getSelection().getActionCommand());
            pst.setInt(5,codFornecedor);
            pst.setInt(6,codEpi);
            pst.setInt(7, Integer.parseInt(textNcaixa.getText().trim()));
            pst.setInt(8, Integer.parseInt(textUcaixa.getText().trim()));
            pst.execute();
            pst.close();
            JOptionPane.showMessageDialog(null, "Salvo com Sucesso!");
            salvarQtd();
            Cancelar();
            conexao.desconecta();
        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao salvar\n" + erro);
        }
        conexao.desconecta();
    }//GEN-LAST:event_btnSalvarActionPerformed

    private void btnCalcularActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCalcularActionPerformed
        valor1 = Integer.parseInt(textNcaixa.getText());
        valor2 = Integer.parseInt(textUcaixa.getText());
        total = valor1 * valor2;
        JOptionPane.showMessageDialog(null, "O total de itens foram:" + total);
        textQuantidade.setText(String.valueOf(total));
    }//GEN-LAST:event_btnCalcularActionPerformed

    private void radioUnidadeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioUnidadeActionPerformed
        selecaoUnidade();
    }//GEN-LAST:event_radioUnidadeActionPerformed

    private void radioCaixaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioCaixaActionPerformed
        selecaoCaixa();
        btnCalcular.setEnabled(true);
    }//GEN-LAST:event_radioCaixaActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
//        try {
//            this.conexao.con.close();
//        } catch (SQLException ex) {
//            JOptionPane.showMessageDialog(null, "Erro ao fecha o formulario"+ex);
//        }
    }//GEN-LAST:event_formWindowClosed

    private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated
//        conexao.conexao();
    }//GEN-LAST:event_formWindowActivated

    public void Novo() {
        formattedData.setEnabled(true);
        textNota.setEnabled(true);
        textNota.requestFocus();
        panelModoEntrada.setEnabled(true);
        radioCaixa.setEnabled(true);
        radioUnidade.setEnabled(true);
        boxEpi.setEnabled(true);
        boxFornecedor.setEnabled(true);
    }

    public void Cancelar() {
        formattedData.setText("");
        textNota.setText("");
        textQuantidade.setText("");
        textNcaixa.setText("");
        textUcaixa.setText("");        
        btnNovo.requestFocus();
        btnGroupModoEntrada.clearSelection();
        boxEpi.setSelectedIndex(0);
        boxFornecedor.setSelectedIndex(0);
        panelModoEntrada.setEnabled(false);
        formattedData.setEnabled(false);
        textNota.setEnabled(false);
        textQuantidade.setEnabled(false);
        boxEpi.setEnabled(false);
        boxFornecedor.setEnabled(false);
        radioCaixa.setEnabled(false);
        radioUnidade.setEnabled(false);
        textNcaixa.setEnabled(false);
        textUcaixa.setEnabled(false);
    }

    private void ComboEpi() {
        try {
            conexao.conexao();
            conexao.pst = conexao.con.createStatement();
            conexao.rs = conexao.pst.executeQuery("SELECT * FROM cadastroepi order by nome_epi");
            boxEpi.addItem("Selecione o EPI");
            while (conexao.rs.next()) {
                boxEpi.addItem(conexao.rs.getObject(2));
            }
            conexao.rs.close();
            conexao.desconecta();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao preencher box \n" + ex);
            conexao.desconecta();
        }
        //conexao.desconecta();
    }

    private void ComboFornecedor() {
        try {
            conexao.conexao();
            conexao.pst = conexao.con.createStatement();
            conexao.rs = conexao.pst.executeQuery("SELECT * FROM cadastrofabricante order by nome_fabricante");
            boxFornecedor.addItem("Selecione o Fornecedor");
            while (conexao.rs.next()) {
                boxFornecedor.addItem(conexao.rs.getObject(4));
            }
            conexao.rs.close();
           conexao.desconecta();
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Erro ao preencher ComboBoxFornecedor \n" + ex);
            conexao.desconecta();
        }
    }

    public void selecaoUnidade() {
        opcao = btnGroupModoEntrada.getSelection().getActionCommand();
        if ("unidade".equals(opcao)) {
            textQuantidade.setEnabled(true);
        }
    }

    public void selecaoCaixa() {
        opcao = btnGroupModoEntrada.getSelection().getActionCommand();
        if ("caixa".equals(opcao)) {
            textNcaixa.setEnabled(true);
            textUcaixa.setEnabled(true);
            textQuantidade.setEnabled(true);
        }
    }   
    
    public void buscaCodEpi() {
        conexao.conexao();
        try {           
            conexao.executaSQL("select * from cadastroepi where nome_epi ='" + this.epiEntrada + "'");
            conexao.rs.first();
            codEpi = conexao.rs.getInt("idcad_epi");
        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao preencher ComboBoxSetor \n" + erro);
              conexao.desconecta(); 
        }       
    }
    
    public void buscaCodFornecedor() {
        conexao.conexao();
        try {           
            conexao.executaSQL("select * from cadastrofabricante where nome_fabricante ='" +this.fornecedorEntrada+"'");
            conexao.rs.first();
            codFornecedor = conexao.rs.getInt("idfabricante");
        } catch (SQLException erro) {
            JOptionPane.showMessageDialog(null, "Erro ao preencher ComboBoxSetor \n" + erro);
            conexao.desconecta();
        }       
        conexao.desconecta();
    }
    
    private Date converteData(String data) {                    
        Date d = null;     
        try {     
            data = data.substring(6) + "-" +     
                    data.substring(3, 5) + "-" +     
                    data.substring(0, 2);     
            d = Date.valueOf(data);     
        } catch (Exception ex) {     
            ex.printStackTrace();     
        }     
        return d;     
    } 
    
    private void salvarQtd(){        
       //conexao.executaSQL("select sum(tbepi.quantidade_epi) + sum(tbent.quantidade_entrada) as total from cadastroepi tbepi, entradaepi tbent where (tbent.idcad_epi = tbepi.idcad_epi)");
        
    }
    
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Frm_Acesso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Frm_Acesso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Frm_Acesso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Frm_Acesso.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Frm_EntradaEpi().setVisible(true);
            }
        });
    }
    
 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JComboBox boxEpi;
    private javax.swing.JComboBox boxFornecedor;
    private javax.swing.JButton btnCalcular;
    private javax.swing.JButton btnCancelar;
    private javax.swing.ButtonGroup btnGroupModoEntrada;
    private javax.swing.JButton btnNovo;
    private javax.swing.JButton btnSalvar;
    private javax.swing.JFormattedTextField formattedData;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JLabel lblData;
    private javax.swing.JLabel lblEntradaEpi;
    private javax.swing.JLabel lblEscoEPI;
    private javax.swing.JLabel lblEscoFornecedor;
    private javax.swing.JLabel lblIdEntrada;
    private javax.swing.JLabel lblNumeroNF;
    private javax.swing.JLabel lblQuantidade;
    private javax.swing.JLabel lblUnidades;
    private javax.swing.JPanel panelModoEntrada;
    private javax.swing.JRadioButton radioCaixa;
    private javax.swing.JRadioButton radioUnidade;
    private javax.swing.JTextField textIdEntrada;
    private javax.swing.JTextField textNcaixa;
    private javax.swing.JTextField textNota;
    private javax.swing.JTextField textQuantidade;
    private javax.swing.JTextField textUcaixa;
    // End of variables declaration//GEN-END:variables
}
